package com.cmdi.mq.demo1;

import io.netty.channel.DefaultChannelId;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @Description: 消费消息
 * @Author: gaozb
 */
public class ConsumerOrdered {
    public static void main(String[] args) throws Exception {
        //指定消费者组，如果没有consumer-group需要首先创建
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-group2");
        // 设置NameServer的地址
        consumer.setNamesrvAddr("10.254.243.246:9876;10.254.243.249:9876");
        // 设置从哪读取，失效？
        //consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 订阅的topic，可将*换成tag名
        consumer.subscribe("topic1","*");
        /**
         * 注意：顺序消费MessageListenerOrderly下BROADCASTING广播模式无效
         **/
        consumer.setMessageModel(MessageModel.CLUSTERING);
        //设置消费监听Orderl
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                consumeOrderlyContext.setAutoCommit(true);
                for (MessageExt messageExt : list) {
                    System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), new String(messageExt.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        //解决invokeSync call timeout异常
        DefaultChannelId.newInstance();
        //启动消费
        consumer.start();
        System.out.printf("Consumer Started.%n");
    }
}